<template>
  <div class="question-space-container">
    <div class="question-space">
      <!-- 返回按钮 和 标题 -->
      <div class="header">
        <div class="back-button">
          <i class="el-icon-arrow-left"></i>
        </div>
        <h1 class="title" style="background-color: transparent;">问答空间</h1>
      </div>

      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
            v-model="searchText"
            placeholder="搜索您感兴趣的问题"
            prefix-icon="el-icon-search"
            clearable
            @keyup.enter.native="searchQuestions"
        ></el-input>
      </div>

      <!-- 问题列表 -->
      <div class="question-list">
        <!-- 暂无数据 -->
        <div v-if="!loading && questionList.length === 0" class="no-data">
          暂无问题数据
        </div>

        <el-card v-for="item in questionList" :key="item.id" class="question-card"
                 @click.native="goToQuestionDetail(item.id)">
          <div class="question-header">
            <div class="user-info">
              <div class="avatar">
                <!-- 用户头像 -->
                <img :src="item.avatar"/>
              </div>
              <span class="username">{{ item.publisher }}</span>
            </div>
            <!-- 热门标签，当isTop为1时显示 -->
            <div v-if="item.isTop === 1" class="hot-tag">热门</div>
          </div>

          <div class="question-content">
            <h3 class="question-title" style="color: #000000">{{ item.title }}</h3>
            <p class="question-description" style="color: #000000">{{ item.description }}</p>
          </div>

          <div class="question-footer">
            <span class="reply-count" style="color: #000000">已有 {{ item.replyCount || 0 }} 人参与讨论</span>
          </div>
        </el-card>

        <!-- 加载更多 -->
        <div v-if="loading" class="loading">
          <el-loading-text>加载中...</el-loading-text>
        </div>
      </div>

      <!-- 提问按钮 -->
      <div class="ask-button" @click="goToAskQuestion">
        <el-button type="primary" round>
          <i class="el-icon-plus"></i> 提问
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {sendRequest} from '@/util/request';

export default {
  name: 'QuesList',
  data() {
    return {
      questionList: [], // 问题列表
      searchText: '', // 搜索内容
      loading: false, // 加载状态
      bannerImage: 'https://fontmeme.com/temporary/re_9143_userlmn_36e04222d3a0.jpg', // 头图URL，需要从后台配置获取
    };
  },
  created() {
    this.getQuestionList();
  },
  methods: {
    // 1. 首先修改 getQuestionList 方法，使用 Promise.all 同时处理两个请求
    getQuestionList() {
      this.loading = true;
      // 同时发起两个请求
      Promise.all([
        sendRequest('get', '/ques/list'),
        sendRequest('get', '/user/list')
      ]).then(([quesRes, userRes]) => {
            if (quesRes.code === 200 && userRes.code === 200) {
              // 创建用户信息的Map，方便查找
              const userMap = new Map(
                  userRes.rows.map(user => [user.id, user])
              );
              // 处理问题列表，合并用户信息
              this.questionList = quesRes.rows
                  .filter(item => item.isHidden !== 1)
                  .map(question => ({
                    ...question,
                    // 假设问题中有 userId 字段关联用户
                    avatar: userMap.get(question.userId)?.avatar,
                    // 其他需要的用户信息也可以在这里添加
                    publisher: userMap.get(question.userId)?.username || question.publisher
                  }))
                  .sort((a, b) => {
                    if (a.isTop !== b.isTop) {
                      return b.isTop - a.isTop;
                    }
                    return new Date(b.publishTime) - new Date(a.publishTime);
                  });
              // 获取回答数量
              this.questionList.forEach(question => {
                this.getReplyCount(question.id);
              });
            }
            this.loading = false;
          })
          .catch(error => {
            console.error('获取数据失败', error);
            this.loading = false;
          });
    },
    searchQuestions() {
      this.loading = true;
      // 调用后端搜索接口，搜索用户名、问题标题或问题内容
      const params = {
        title: this.searchText,
        description: this.searchText,
        publisher: this.searchText
      };
      sendRequest('get', '/ques/list', params)
          .then(res => {
            if (res.code === 200) {
              this.questionList = res.rows
                  .filter(item => item.isHidden !== 1) // 过滤掉isHidden=1的问题
                  .sort((a, b) => {
                    if (a.isTop !== b.isTop) {
                      return b.isTop - a.isTop;
                    }
                    return new Date(b.publishTime) - new Date(a.publishTime);
                  });

              // 为每个搜索结果获取回答数量
              this.questionList.forEach(question => {
                this.getReplyCount(question.id);
              });
            }
            this.loading = false;
          })
          .catch(error => {
                console.error('搜索问题失败', error);
                this.loading = false;
              }
          );
    },
    getReplyCount(quesId) {
      // 通过space_answer表查询quesId下的回答数量
      const params = {quesId: quesId};
      sendRequest('get', '/answer/list', params)
          .then(res => {
            if (res.code === 200) {
              // 仅过滤当前quesId的回答
              const currentQuesAnswers = res.rows.filter(answer => answer.quesId === quesId);
              // 计算唯一用户（通过phone字段区分）的数量
              const uniquePhones = new Set();
              if (currentQuesAnswers && currentQuesAnswers.length > 0) {
                currentQuesAnswers.forEach(answer => {
                  if (answer.phone) {
                    uniquePhones.add(answer.phone);
                  }
                });
              }
              // 更新问题的回答数量为唯一用户数
              const questionIndex = this.questionList.findIndex(q => q.id === quesId);
              if (questionIndex !== -1) {
                this.$set(this.questionList[questionIndex], 'replyCount', uniquePhones.size);
              }
            }
          })
          .catch(error => {
            console.error(`获取问题ID ${quesId} 的回答数量失败`, error);
          });
      // 返回当前已有的replyCount，后续异步更新
      const question = this.questionList.find(q => q.id === quesId);
      return question ? question.replyCount || 0 : 0;
    },
    // 跳转到问题详情页
    goToQuestionDetail(id) {
      this.$router.push({
        path: '/ques/detail',
        query: {id}
      });
    },

    // 跳转到提问页面
    goToAskQuestion() {
      this.$router.push({
        path: '/ques/ask'
      });
    }
  }
};
</script>
<style scoped>
.question-space-container {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.question-space {
  position: relative;
  width: 33.33%;
  height: 100vh;
  background-color: #fff;
  background-image: url('E:/zhizhiniao1-ui/bird1-ui/src/assets/re_8640_userlmn_566c912f88a7.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: transparent;
  z-index: 20;
  text-align: center;
}

.back-button {
  position: absolute;
  left: 15px;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.title {
  width: 100%;
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  background-color: transparent;
}

.search-container {
  padding: 0 20px;
  margin: 10px 0 20px;
}

.search-container .el-input >>> .el-input__inner {
  border-radius: 30px;
  height: 40px;
  padding-left: 40px;
}

.search-container .el-input >>> .el-input__prefix {
  left: 15px;
}

.question-list {
  flex: 1;
  padding: 0 20px;
  overflow-y: auto;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #000;
  font-size: 16px;
}

.question-card {
  margin-bottom: 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid red;
  background-color: transparent;
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.username {
  font-size: 14px;
  color: #333;
}

.hot-tag {
  background-color: #ff6b6b;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.question-content {
  margin-bottom: 10px;
}

.question-title {
  font-size: 16px;
  margin-bottom: 8px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.question-description {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.question-footer {
  font-size: 12px;
  color: #999;
}

.reply-count {
  font-size: 12px;
}

.loading {
  text-align: center;
  padding: 20px 0;
  color: #999;
}

.ask-button {
  position: absolute;
  right: 15px;
  bottom: 15px;
  z-index: 100;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
  border-radius: 30px;
  padding: 12px 24px;
  font-size: 16px;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.5);
}

.el-button--primary i {
  margin-right: 5px;
}

/* 在小屏幕设备上自适应宽度 */
@media (max-width: 1200px) {
  .question-space {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .question-space {
    width: 95%;
  }
}
</style>
